﻿using Heima.OA.Common;
using Heima.OA.IBLL;
using Heima.OA.Model;
using Heima.OA.UI.Portal.Controllers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Mvc;

namespace Heima.OA.UI.Portal.Areas.Declare.Controllers
{
    public class AttachmentController : BaseController
    {
        public IZS_AttachmentService ZS_AttachmentService { get; set; }
        // GET: Declare/Attachment
        public string Index(PaginationQuery paginationQuery)
        {
            int total = 0;
            var attachmentList = ZS_AttachmentService.GetPageEntities(paginationQuery.pagesize, paginationQuery.pageindex, out total, u => u.DelFlag == delflagNormal,
                s => s.CreateTime, true).AsQueryable();

            PaginationData data = new PaginationData() { total = total, rows = JsonHandler.ToJson(attachmentList) };
            JsonMessage msg = JsonHandler.CreateMessage((int)MsgTypeEnum.成功, "", JsonHandler.ToJson(data));

            return JsonHandler.ToJson(msg);
        }

        #region 上传附件
        [HttpPost]
        public string UploadAttachment()
        {
            string res = string.Empty;
            if (Request.Files.Count > 0)
            {
                HttpPostedFileBase file = Request.Files[0];
                //附件大于50M禁止上传
                if (file.ContentLength > 1024 * 1000 * 50)
                {
                    JsonMessage message = JsonHandler.CreateMessage((int)MsgTypeEnum.错误, "附件大于50M,上传失败!");
                    res = JsonHandler.ToJson(message);
                }
                else
                {
                    string[] arr = file.FileName.Split('.');
                    string uniqueName = Guid.NewGuid().ToString();
                    string folders = ConstData.GetAttaPathByExtension(arr[1]);
                    string path = folders + uniqueName + "." + arr[1];
                    string mapFolders = Request.MapPath(folders);
                    if (!FileUpload.Exists(mapFolders))
                    {
                        FileUpload.MakeDirectory(mapFolders);
                    }
                    string mapPath = Request.MapPath(path);
                    file.SaveAs(mapPath);
                    object obj = new { path = path, filename = arr[0] };

                    JsonMessage message = JsonHandler.CreateMessage((int)MsgTypeEnum.成功, "上传成功!", JsonHandler.ToJson(obj));
                    res = JsonHandler.ToJson(message);
                }
            }
            else
            {
                JsonMessage message = JsonHandler.CreateMessage((int)MsgTypeEnum.成功, "上传失败!");
                res = JsonHandler.ToJson(message);
            }
            return res;
        }

        #endregion
        [HttpPost]
        public string UploadFile(ZS_Attachment attachment)
        {
            string res = string.Empty;
            if (Request.Files.Count > 0)
            {
                HttpPostedFileBase file = Request.Files[0];
                //附件大于50M禁止上传
                if (file.ContentLength > 1024 * 1000 * 50)
                {
                    JsonMessage message = JsonHandler.CreateMessage((int)MsgTypeEnum.错误, "附件大于50M,上传失败!");
                    res = JsonHandler.ToJson(message);
                }
                else
                {
                    string[] arr = file.FileName.Split('.');
                    string uniqueName = Guid.NewGuid().ToString();
                    string folders = ConstData.GetAttaPathByExtension(arr[1]);
                    string path = folders + uniqueName + "." + arr[1];
                    string mapFolders = Request.MapPath(folders);
                    if (!FileUpload.Exists(mapFolders))
                    {
                        FileUpload.MakeDirectory(mapFolders);
                    }
                    string mapPath = Request.MapPath(path);
                    file.SaveAs(mapPath);
                    //attachment.AttaName = arr[0];
                    attachment.AttaType = arr[1];
                    attachment.UniqueName = uniqueName;
                    attachment.FilePath = path;
                    attachment.DelFlag = delflagNormal;
                    attachment.CreateTime = DateTime.Now;
                    attachment.CreateOperator = LoginUser.UName;
                    attachment.CreateOperatorId = LoginUser.Id;
                    ZS_AttachmentService.Add(attachment);

                    object obj = new { path = path, filename = arr[0] };
                    JsonMessage message = JsonHandler.CreateMessage((int)MsgTypeEnum.成功, "上传成功!", JsonHandler.ToJson(obj));
                    res = JsonHandler.ToJson(message);
                }
            }
            else
            {
                JsonMessage message = JsonHandler.CreateMessage((int)MsgTypeEnum.成功, "上传失败!");
                res = JsonHandler.ToJson(message);
            }
            return res;
        }

        #region 添加
        public string Create(ZS_Attachment attachment)
        {
            string res = string.Empty;
            if (!string.IsNullOrEmpty(attachment.FilePath))
            {
                attachment.UniqueName = Path.GetFileName(attachment.FilePath).Split('.')[0];
                attachment.AttaType = Path.GetFileName(attachment.FilePath).Split('.')[1];
            }
            attachment.BusinessType = attachment.BusinessType;
            attachment.DataId = 0;
            attachment.DelFlag = delflagNormal;
            attachment.CreateTime = DateTime.Now;
            attachment.CreateOperator = LoginUser.UName;
            attachment.CreateOperatorId = LoginUser.Id;

            ZS_AttachmentService.Add(attachment);
            JsonMessage message = JsonHandler.CreateMessage((int)MsgTypeEnum.成功, "添加成功!");
            res = JsonHandler.ToJson(message);
            return res;
        }

        #endregion
        #region 编辑
        public string Edit(ZS_Attachment attachment)
        {
            ZS_Attachment editAttachment = ZS_AttachmentService.GetModel(attachment.Id);
            string res = string.Empty;
            if (editAttachment == null)
            {
                res = JsonHandler.ToJson(JsonHandler.CreateMessage((int)MsgTypeEnum.错误, "编辑错误!"));
            }
            else
            {
                if (!string.IsNullOrEmpty(attachment.FilePath))
                {
                    editAttachment.UniqueName = Path.GetFileName(attachment.FilePath).Split('.')[0];
                    editAttachment.AttaType = Path.GetFileName(attachment.FilePath).Split('.')[1];
                }
                editAttachment.FilePath = attachment.FilePath;
                editAttachment.AttaName = attachment.AttaName;
                editAttachment.Remark = attachment.Remark;
                editAttachment.BusinessType = attachment.BusinessType;

                bool success = ZS_AttachmentService.Update(editAttachment);
                if (success)
                {
                    res = JsonHandler.ToJson(JsonHandler.CreateMessage((int)MsgTypeEnum.成功, "编辑成功!"));
                }
            }

            return res;
        }
        #endregion
        #region 删除
        public string Delete(int id)
        {
            ZS_Attachment attachment = ZS_AttachmentService.GetModel(id);
            string res = string.Empty;
            if (attachment == null)
            {
                res = JsonHandler.ToJson(JsonHandler.CreateMessage((int)MsgTypeEnum.错误, "删除错误!"));
            }
            else
            {
                attachment.DelFlag = (int)DelFlagEnum.Deleted;
                bool success = ZS_AttachmentService.Update(attachment);
                //文件从磁盘上移动到备份文件夹 日后无用可以删除掉
                if (!string.IsNullOrEmpty(attachment.FilePath))
                {
                    string mapPath = Request.MapPath(attachment.FilePath);
                    FileInfo fileInfo = new FileInfo(mapPath);
                    string backPath = Request.MapPath(ConstData.AttachmentBackPath);
                    if (!FileUpload.Exists(backPath))
                    {
                        FileUpload.MakeDirectory(backPath);
                    }
                    fileInfo.MoveTo(backPath + attachment.AttaName + "." + attachment.AttaType);
                }
                if (success)
                {
                    res = JsonHandler.ToJson(JsonHandler.CreateMessage((int)MsgTypeEnum.成功, "删除成功!"));
                }
            }
            return res;
        }
        #endregion

        #region 下载二进制流文件
        [HttpPost]
        public string DownloadFileBinary(int Id)
        {
            ZS_Attachment attachment = ZS_AttachmentService.GetModel(Id);
            JsonMessage msg = new JsonMessage();
            if (attachment != null)
            {
                string filePath = Server.MapPath(attachment.FilePath);//路径
                FileInfo fileinfo = new FileInfo(filePath);
                Response.Clear();         //清除缓冲区流中的所有内容输出
                Response.ClearContent();  //清除缓冲区流中的所有内容输出
                Response.ClearHeaders();  //清除缓冲区流中的所有头
                //Response.Buffer = true;   //该值指示是否缓冲输出，并在完成处理整个响应之后将其发送
                Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(attachment.AttaName, System.Text.Encoding.UTF8));
                Response.AddHeader("Content-Length", fileinfo.Length.ToString());
                //Response.AddHeader("Content-Transfer-Encoding", "binary");
                Response.ContentType = "application/oct-stream";  //获取或设置输出流的 HTTP MIME 类型
                Response.TransmitFile(filePath);
                Response.End();
            }
            else
            {
                msg = JsonHandler.CreateMessage((int)MsgTypeEnum.错误, "下载失败!");
            }
            return JsonHandler.ToJson(msg);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage DownloadFile(int Id)
        {
            ZS_Attachment attachment = ZS_AttachmentService.GetModel(Id);
            JsonMessage msg = new JsonMessage();
            if (attachment != null)
            {
                string filePath = Server.MapPath(attachment.FilePath);//路径
                string fileName = Path.GetFileName(filePath);
                //string mime = MimeMapping.GetMimeMapping(fileName);
                //return File(filePath, mime, fileName);
                HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
                var stream = new FileStream(filePath, FileMode.Open);
                result.Content = new StreamContent(stream);
                result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                result.Content.Headers.ContentDisposition.FileName = fileName;
                result.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(fileName));
                result.Content.Headers.ContentLength = stream.Length;
                return result;
            }
            else
            {
                return null;
            }
        }
        #endregion

    }
}